<template>
  <el-dialog :title="title" v-model="dialogVisible" width="600px" destroy-on-close @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" :disabled="type === 'edit'" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="type === 'add'">
        <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-input v-model="form.avatar" placeholder="请输入头像地址" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="角色">
        <el-scrollbar height="200px" class="tree-container">
          <el-tree
            ref="roleTreeRef"
            :data="roleOptions"
            show-checkbox
            node-key="role_id"
            :props="{
              label: 'name',
              children: 'children',
              disabled: (node) => node.code === 'super_admin'
            }"
            :default-checked-keys="form.role_ids"
          />
        </el-scrollbar>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import type { FormInstance, ElTree } from 'element-plus'
import { ElMessage } from 'element-plus'
import { createAdmin, updateAdmin } from '/@/api/admin'
import { getRoleList } from '/@/api/role'
import type { AdminForm } from '/@/api/admin'

const props = defineProps<{
  visible: boolean
  type: 'add' | 'edit'
  currentRow?: any
}>()

const emit = defineEmits(['update:visible', 'success'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const title = computed(() => props.type === 'add' ? '新增管理员' : '编辑管理员')

const formRef = ref<FormInstance>()
const roleTreeRef = ref<InstanceType<typeof ElTree>>()
const roleOptions = ref([])

const defaultForm: AdminForm = {
  username: '',
  password: '',
  nickname: '',
  avatar: '',
  status: 1,
  role_ids: [],
}

const form = reactive<AdminForm>({ ...defaultForm })

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
}

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const { data } = await getRoleList({ pageSize: 999 })
    roleOptions.value = data.list
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

// 初始化表单数据
const initFormData = () => {
  if (props.type === 'edit' && props.currentRow) {
    Object.assign(form, props.currentRow)
    form.role_ids = Array.isArray(form.role_ids) ? form.role_ids : []
  } else {
    Object.assign(form, defaultForm)
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 获取选中的角色ID
        form.role_ids = roleTreeRef.value?.getCheckedKeys(false) as number[]
        
        if (props.type === 'add') {
          await createAdmin(form)
          ElMessage.success('新增成功')
        } else {
          await updateAdmin(form)
          ElMessage.success('更新成功')
        }
        emit('success')
        handleClose()
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 监听visible变化
watch(() => props.visible, (val) => {
  if (val) {
    initFormData()
    fetchRoleList()
  }
})
</script>

<style lang="scss" scoped>
.tree-container {
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  width: 100%;
}
</style> 